package com.ssm.sport.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ssm.sport.entity.Order;
import com.ssm.sport.entity.OrderItem;
import com.ssm.sport.entity.Product;
import com.ssm.sport.entity.Shipping;
import com.ssm.sport.mapper.OrderItemMapper;
import com.ssm.sport.mapper.OrderMapper;
import com.ssm.sport.mapper.ShippingMapper;
import com.ssm.sport.service.CartService;
import com.ssm.sport.service.OrderService;
import com.ssm.sport.service.ProductService;
import com.ssm.sport.vo.CartVO;
import com.ssm.sport.vo.OrderItemVO;
import com.ssm.sport.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 订单服务实现类
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderItemMapper orderItemMapper;
    
    @Autowired
    private CartService cartService;
    
    @Autowired
    private ProductService productService;
    
    @Autowired
    private ShippingMapper shippingMapper;
    
    @Override
    @Transactional
    public OrderVO createOrder(Integer userId, Integer shippingId) {
        // 生成订单号
        String orderNo = generateOrderNo();
        System.out.println("创建订单：用户ID=" + userId + "，收货地址ID=" + shippingId + "，生成订单号=" + orderNo);
        
        // 获取购物车中已勾选的商品
        List<CartVO> cartItems = cartService.getCheckedCartItems(userId);
        if (CollectionUtils.isEmpty(cartItems)) {
            throw new RuntimeException("购物车中没有选中的商品");
        }
        
        // 计算订单总价
        BigDecimal payment = calculateOrderTotalPrice(cartItems);
        
        // 获取收货地址
        Shipping shipping = shippingMapper.selectById(shippingId);
        
        // 如果没有找到指定的收货地址，尝试获取默认地址
        if (shipping == null) {
            shipping = shippingMapper.selectDefaultShipping(userId);
            
            // 如果还是没有，尝试获取用户的任意一个地址
            if (shipping == null) {
                List<Shipping> userAddresses = shippingMapper.selectByUserId(userId);
                if (!CollectionUtils.isEmpty(userAddresses)) {
                    shipping = userAddresses.get(0);
                    // 更新shippingId为实际使用的地址ID
                    shippingId = shipping.getId();
                    System.out.println("未找到指定地址，已自动使用用户的第一个地址，ID: " + shippingId);
                } else {
                    throw new RuntimeException("收货地址不存在，请先添加收货地址");
                }
            } else {
                // 更新shippingId为默认地址ID
                shippingId = shipping.getId();
                System.out.println("未找到指定地址，已自动使用默认地址，ID: " + shippingId);
            }
        }
        
        // 创建订单
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(userId);
        order.setShippingId(shippingId);
        order.setPayment(payment);
        order.setPaymentType(1); // 在线支付
        order.setPostage(new BigDecimal("0")); // 运费
        order.setStatus(10); // 未付款
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        
        orderMapper.insert(order);
        
        // 创建订单明细
        List<OrderItem> orderItems = createOrderItems(userId, orderNo, cartItems);
        for (OrderItem orderItem : orderItems) {
            orderItemMapper.insert(orderItem);
            
            // 扣减库存 (这里简化处理，实际应该在商品服务中实现)
            Product product = productService.getById(orderItem.getProductId());
            product.setStock(product.getStock() - orderItem.getQuantity());
            productService.updateById(product);
        }
        
        // 清空购物车中已购买的商品
        for (CartVO cartItem : cartItems) {
            cartService.deleteFromCart(userId, cartItem.getProductId());
        }
        
        // 组装OrderVO对象返回
        return assembleOrderVO(order, orderItems, shipping);
    }

    @Override
    public boolean cancelOrder(Integer userId, String orderNo) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("order_no", orderNo);
        
        Order order = orderMapper.selectOne(queryWrapper);
        if (order == null) {
            return false;
        }
        
        // 只有未付款状态的订单可以取消
        if (order.getStatus() != 10) {
            return false;
        }
        
        order.setStatus(50); // 已关闭
        order.setCloseTime(new Date());
        order.setUpdateTime(new Date());
        
        return orderMapper.updateById(order) > 0;
    }

    @Override
    public OrderVO getOrderDetail(Integer userId, String orderNo) {
        // 查询订单
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_no", orderNo);
        
        // 当userId不为null时，添加用户ID限制条件
        if (userId != null) {
            orderQueryWrapper.eq("user_id", userId);
        }
        
        Order order = orderMapper.selectOne(orderQueryWrapper);
        
        if (order == null) {
            return null;
        }
        
        // 查询订单明细
        List<OrderItem> orderItems = orderItemMapper.selectByOrderNo(orderNo);
        
        // 查询收货地址
        Shipping shipping = shippingMapper.selectById(order.getShippingId());
        
        // 组装OrderVO返回
        return assembleOrderVO(order, orderItems, shipping);
    }

    @Override
    public Page<OrderVO> getOrderList(Integer userId, int pageNum, int pageSize) {
        // 分页查询用户订单
        Page<Order> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .orderByDesc("create_time");
        
        orderMapper.selectPage(page, queryWrapper);
        
        // 转换为OrderVO列表
        List<OrderVO> orderVOList = new ArrayList<>();
        for (Order order : page.getRecords()) {
            // 查询订单明细
            List<OrderItem> orderItems = orderItemMapper.selectByOrderNo(order.getOrderNo());
            
            // 查询收货地址
            Shipping shipping = shippingMapper.selectById(order.getShippingId());
            
            // 组装OrderVO
            OrderVO orderVO = assembleOrderVO(order, orderItems, shipping);
            orderVOList.add(orderVO);
        }
        
        // 创建新的Page对象返回
        Page<OrderVO> resultPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        resultPage.setRecords(orderVOList);
        
        return resultPage;
    }

    @Override
    public Page<OrderVO> getAllOrderList(int pageNum, int pageSize) {
        // 分页查询所有订单
        Page<Order> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        
        orderMapper.selectPage(page, queryWrapper);
        
        // 转换为OrderVO列表
        List<OrderVO> orderVOList = new ArrayList<>();
        for (Order order : page.getRecords()) {
            // 查询订单明细
            List<OrderItem> orderItems = orderItemMapper.selectByOrderNo(order.getOrderNo());
            
            // 查询收货地址
            Shipping shipping = shippingMapper.selectById(order.getShippingId());
            
            // 组装OrderVO
            OrderVO orderVO = assembleOrderVO(order, orderItems, shipping);
            orderVOList.add(orderVO);
        }
        
        // 创建新的Page对象返回
        Page<OrderVO> resultPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        resultPage.setRecords(orderVOList);
        
        return resultPage;
    }

    @Override
    @Transactional
    public boolean sendOrder(String orderNo) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        
        Order order = orderMapper.selectOne(queryWrapper);
        if (order == null) {
            return false;
        }
        
        // 只有已付款状态的订单可以发货
        if (order.getStatus() != 20) {
            return false;
        }
        
        order.setStatus(30); // 已发货
        order.setSendTime(new Date());
        order.setUpdateTime(new Date());
        
        return orderMapper.updateById(order) > 0;
    }

    @Override
    @Transactional
    public boolean payOrder(Integer userId, String orderNo) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("order_no", orderNo);
        
        Order order = orderMapper.selectOne(queryWrapper);
        if (order == null) {
            return false;
        }
        
        // 只有未付款状态的订单可以支付
        if (order.getStatus() != 10) {
            return false;
        }
        
        order.setStatus(20); // 已付款
        order.setPaymentTime(new Date());
        order.setUpdateTime(new Date());
        
        return orderMapper.updateById(order) > 0;
    }
    
    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }
    
    /**
     * 计算订单总价
     */
    private BigDecimal calculateOrderTotalPrice(List<CartVO> cartItems) {
        BigDecimal totalPrice = new BigDecimal("0");
        
        for (CartVO cartItem : cartItems) {
            totalPrice = totalPrice.add(cartItem.getProductTotalPrice());
        }
        
        return totalPrice;
    }
    
    /**
     * 创建订单明细
     */
    private List<OrderItem> createOrderItems(Integer userId, String orderNo, List<CartVO> cartItems) {
        List<OrderItem> orderItems = new ArrayList<>();
        
        for (CartVO cartItem : cartItems) {
            OrderItem orderItem = new OrderItem();
            orderItem.setUserId(userId);
            orderItem.setOrderNo(orderNo);
            orderItem.setProductId(cartItem.getProductId());
            orderItem.setProductName(cartItem.getProductName());
            orderItem.setProductImage(cartItem.getProductImage());
            orderItem.setCurrentUnitPrice(cartItem.getProductPrice());
            orderItem.setQuantity(cartItem.getQuantity());
            orderItem.setTotalPrice(cartItem.getProductTotalPrice());
            orderItem.setCreateTime(new Date());
            orderItem.setUpdateTime(new Date());
            
            orderItems.add(orderItem);
        }
        
        return orderItems;
    }
    
    /**
     * 组装OrderVO对象
     */
    private OrderVO assembleOrderVO(Order order, List<OrderItem> orderItems, Shipping shipping) {
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        
        // 设置收货地址信息
        if (shipping != null) {
            orderVO.setReceiverName(shipping.getReceiverName());
            orderVO.setReceiverPhone(shipping.getReceiverPhone());
            orderVO.setReceiverProvince(shipping.getReceiverProvince());
            orderVO.setReceiverCity(shipping.getReceiverCity());
            orderVO.setReceiverDistrict(shipping.getReceiverDistrict());
            orderVO.setReceiverAddress(shipping.getReceiverAddress());
            orderVO.setReceiverZip(shipping.getReceiverZip());
        }
        
        // 设置订单明细
        List<OrderItemVO> orderItemVOList = new ArrayList<>();
        for (OrderItem orderItem : orderItems) {
            OrderItemVO orderItemVO = new OrderItemVO();
            BeanUtils.copyProperties(orderItem, orderItemVO);
            orderItemVOList.add(orderItemVO);
        }
        orderVO.setOrderItemVOList(orderItemVOList);
        
        return orderVO;
    }

    @Override
    public long count() {
        return orderMapper.selectCount(null);
    }
    
    @Override
    public long getTodayOrderCount() {
        // 获取今天的开始和结束时间
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date startTime = calendar.getTime();
        
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        Date endTime = calendar.getTime();
        
        // 创建查询条件
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("create_time", startTime, endTime);
        
        return orderMapper.selectCount(queryWrapper);
    }
    
    @Override
    public long getPendingOrderCount() {
        // 查询待发货订单数量
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 20); // 已支付，待发货
        
        return orderMapper.selectCount(queryWrapper);
    }
    
    @Override
    public BigDecimal getTotalSales() {
        // 查询所有已支付的订单
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("status", 20, 30, 40); // 已支付、已发货、已完成
        
        List<Order> orders = orderMapper.selectList(queryWrapper);
        
        // 计算总销售额
        return orders.stream()
                .map(Order::getPayment)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
} 